<?php
require_once(dirname(__FILE__)."/../lib/Loader.php");
cfgload("defines");
cload("Smarty.smartyRenderer");
cload("database.dbquery");
cload("advRating.advRatingConvertor");
cload("requestProcessor");

/**
 * Description of ratingConvertor
 *
 * @author Di_Moon
 */
class ratingConvertor extends smartyRenderer {
    protected $_dbh;
    
    function __construct($dbh) {
        parent::__construct();
        
        $this->_dbh = $dbh;
        
    }
    
    function showList() {
        $sql = new dbquery($this->_dbh);
        $sql->select()->from("advRatingConvertor")->order("country asc");
        $sth = $this->_dbh->query($sql);
        
        $arr = array();
        while($fa = $this->_dbh->raw_fetch_array($sth)) {
            array_push($arr, $fa);
        }

        $this->assign("convertList", $arr);
        
        return $this->fetch("ratingConvertorList.tpl");
    }
    
    function showForm() {
        $country = requestProcessor::getVar("country");
        $rating  = requestProcessor::getVar("rating");
        $converted = requestProcessor::getVar("converted", "");
        $type = (int)requestProcessor::getVar("type", 1);
        
        $conv = new advRatingConvertor($this->_dbh, $country);
        
        $row = $conv->load($rating);
        
        if($converted != "") {
            if($row == null) $row = $conv;
            $row->set("country", $country);
            $row->set("rating", $rating);
            $row->set("converted", $converted);
            $row->set("type", $type);
            
            $row->save();
        }
        
        if($row!=null) {
            $converted = $row->get("converted");
            $type = $row->get("type");
        };
        
        $this->assign("country", $country);
        $this->assign("rating", htmlspecialchars($rating));
        $this->assign("converted", htmlspecialchars($converted));
        $this->assign("type", $type);
        
        $this->assign("countryCodes", _itunes_country_codes());
        
        return $this->fetch("ratingConvertorForm.tpl");
    }
    
    function deleteRow() {
        $country = addslashes(requestProcessor::getVar("country", ""));
        $rating  = addslashes(requestProcessor::getVar("rating", ""));
        
        if($country!="" && $rating!="") {
            $sql = new dbquery($this->_dbh);
            $sql->delete("advRatingConvertor")->where("country='$country' and rating='$rating'");
            $this->_dbh->query($sql);
        }
    }
    
    function render() {
        $action = requestProcessor::getVar("action", "");
        
        if($action=="form") return $this->showForm();
        if($action=="del") $this->deleteRow();
        
        return $this->showList();
    }
}

?>
